package com.zhongfl.crm.service.impl.boss;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.zhongfl.crm.lixiao.mapper.OrderAttachmentMapper;
import com.zhongfl.crm.service.boss.AttachmentService;
import com.zhongfl.crm.service.boss.Url2FileService;
import com.zhongfl.crm.model.boss.OrderAttachment;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;
import tech.heptagram.aliyun.oss.properties.OssInfoProperties;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.Objects;

@Service
public class AttachmentServiceImpl implements AttachmentService {

    private static final String SYSTEM_KEY = "workorder";
    private static final String FILE_NAME_DATE_PATTERN = "yyyymmdd";
    private static final String DEFAULT_STYLE = "image/resize,h_100";
    private static final int DEFAULT_EXPIRATION = 2;

    @Resource(name = "ossShowClient")
    private OSSClient ossShowClient;

    @Resource(name = "ossManagerClient")
    private OSSClient managerClient;

    @Resource(name = "ossProperties")
    private OssInfoProperties ossInfoProperties;

    @Resource
    private OrderAttachmentMapper attachmentMapper;

    @Resource
    private Url2FileService url2FileService;

    /**
     * 生成文件路径
     * 默认规则: 系统标识/yyyymmdd/时间戳-10位随机数.后缀
     * 如: workorder/20180504/121212-121212121212.jpg
     *
     * @param fileName
     * @return
     */
    private String generate(String fileName) {
        StringBuffer buffer = new StringBuffer();
        buffer.append(SYSTEM_KEY).append("/");
        Date date = new Date();
        buffer.append(DateFormatUtils.format(new Date(), FILE_NAME_DATE_PATTERN)).append("/");
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        buffer.append(date.getTime()).append("-").append(RandomStringUtils.randomNumeric(10)).append(".").append(fileType);
        return buffer.toString();
    }

    /**
     * 获取文件地址
     *
     * @return 文件详情
     */
    @Override
    public OrderAttachment getUrl(OrderAttachment attachment) {
        return getUrl(attachment, DEFAULT_STYLE);
    }

    /**
     * 获取文件地址
     *
     * @param style 缩略图样式
     * @return 文件详情
     */
    @Override
    public OrderAttachment getUrl(OrderAttachment attachment, String style) {
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(ossInfoProperties.getBucketName(), attachment.getPath());
        request.setProcess(style);
        request.setMethod(HttpMethod.GET);
        request.setExpiration(DateUtils.addHours(new Date(), DEFAULT_EXPIRATION));
        String thumbnailPath = ossShowClient.generatePresignedUrl(request).toString();
        String accessPath = ossShowClient.generatePresignedUrl(ossInfoProperties.getBucketName(),
                attachment.getPath(),
                DateUtils.addHours(new Date(), DEFAULT_EXPIRATION),
                HttpMethod.GET).toString();

        attachment.setAccessPath(accessPath);
        attachment.setThumbnailPath(thumbnailPath);
        return attachment;
    }

    @Override
    public OrderAttachment save(String filePath, String orderNo, String workOrderNo, String key, String creater) {
        OrderAttachment attachment = new OrderAttachment();
        attachment.setOrderNo(orderNo);
        attachment.setWorkOrderNo(workOrderNo);
        attachment.setCreatedBy(creater);
        attachment.setModifiedBy(creater);
        attachment.setKey(key);
        attachment.setPath(filePath);
        attachmentMapper.insertSelective(attachment);
        return attachment;
    }

    @Override
    public String uploadLxFileInputStream2OSS(String lxFileUrl) {
        if(StringUtils.isEmpty(lxFileUrl)){
            return null;
        }
        InputStream inputStream = this.downloadFileInputStreamFromLxUrl(lxFileUrl);
        if(Objects.isNull(inputStream)){
            return null;
        }
        String newFileName = this.generate(".jpg");
        managerClient.putObject(ossInfoProperties.getBucketName(), newFileName, inputStream);
        return newFileName;
    }

    private InputStream downloadFileInputStreamFromLxUrl(String lxFileUrl) {
        try {
            return url2FileService.getFileInputStreamFromUrl(lxFileUrl);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
